import React, { useState, useEffect } from 'react';
import {
  List,
  Button,
  Input,
  Modal,
  message,
  Popconfirm,
  Typography,
  Tooltip,
  Empty,
  Spin
} from 'antd';
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  CheckOutlined,
  CloseOutlined
} from '@ant-design/icons';
import chatService from '../../services/ChatService';
import '../../styles/SessionList.css';

const { Text } = Typography;

const SessionList = ({ 
  currentSessionId, 
  onSessionSelect, 
  onSessionCreate,
  visible,
  refreshTrigger,
  onClose 
}) => {
  const [sessions, setSessions] = useState([]);
  const [loading, setLoading] = useState(false);
  const [editingSessionId, setEditingSessionId] = useState(null);
  const [editingTitle, setEditingTitle] = useState('');
  const [createModalVisible, setCreateModalVisible] = useState(false);
  const [newSessionTitle, setNewSessionTitle] = useState('');

  // 加载会话列表
  const loadSessions = async () => {
    setLoading(true);
    try {
      const result = await chatService.getSessions();
      if (result.success) {
        setSessions(result.data.sessions || []);
      } else {
        message.error(result.message || '获取会话列表失败');
      }
    } catch (error) {
      console.error('加载会话列表失败:', error);
      message.error('加载会话列表失败');
    } finally {
      setLoading(false);
    }
  };

  // 组件挂载时加载会话列表
  useEffect(() => {
    if (visible) {
      loadSessions();
    }
  }, [visible]);

  // 监听刷新触发器，当外部需要刷新时重新加载会话列表
  useEffect(() => {
    if (visible && refreshTrigger > 0) {
      loadSessions();
    }
  }, [refreshTrigger, visible]);

  // 创建新会话
  const handleCreateSession = async () => {
    if (!newSessionTitle.trim()) {
      message.warning('请输入会话标题');
      return;
    }

    try {
      const result = await chatService.createSession(newSessionTitle.trim());
      if (result.success) {
        message.success('会话创建成功');
        setCreateModalVisible(false);
        setNewSessionTitle('');
        await loadSessions();
        // 自动选择新创建的会话
        if (result.data.session) {
          onSessionCreate && onSessionCreate(result.data.session);
        }
      } else {
        message.error(result.message || '创建会话失败');
      }
    } catch (error) {
      console.error('创建会话失败:', error);
      message.error('创建会话失败');
    }
  };

  // 快速创建会话（使用默认标题）
  const handleQuickCreateSession = async () => {
    try {
      const result = await chatService.createSession();
      if (result.success) {
        message.success('会话创建成功');
        await loadSessions();
        // 自动选择新创建的会话
        if (result.data.session) {
          onSessionCreate && onSessionCreate(result.data.session);
        }
      } else {
        message.error(result.message || '创建会话失败');
      }
    } catch (error) {
      console.error('创建会话失败:', error);
      message.error('创建会话失败');
    }
  };

  // 开始编辑会话标题
  const startEditing = (session) => {
    setEditingSessionId(session.id);
    setEditingTitle(session.session_title);
  };

  // 取消编辑
  const cancelEditing = () => {
    setEditingSessionId(null);
    setEditingTitle('');
  };

  // 保存编辑
  const saveEditing = async () => {
    if (!editingTitle.trim()) {
      message.warning('会话标题不能为空');
      return;
    }

    try {
      const result = await chatService.renameSession(editingSessionId, editingTitle.trim());
      if (result.success) {
        message.success('会话重命名成功');
        setEditingSessionId(null);
        setEditingTitle('');
        await loadSessions();
      } else {
        message.error(result.message || '重命名失败');
      }
    } catch (error) {
      console.error('重命名会话失败:', error);
      message.error('重命名失败');
    }
  };

  // 删除会话
  const handleDeleteSession = async (sessionId) => {
    try {
      const result = await chatService.deleteSession(sessionId);
      if (result.success) {
        message.success('会话删除成功');
        await loadSessions();
        // 如果删除的是当前会话，清除选择
        if (currentSessionId === sessionId) {
          onSessionSelect && onSessionSelect(null);
        }
      } else {
        message.error(result.message || '删除会话失败');
      }
    } catch (error) {
      console.error('删除会话失败:', error);
      message.error('删除会话失败');
    }
  };

  // 选择会话
  const handleSessionSelect = (session) => {
    onSessionSelect && onSessionSelect(session);
  };

  return (
    <div className={`session-list ${visible ? 'visible' : 'hidden'}`}>
      <div className="session-list-header">
        <Button 
          icon={<PlusOutlined />}
          onClick={handleQuickCreateSession}
          className="create-session-button"
        >
          新建对话
        </Button>
      </div>

      <div className="session-list-content">
        {loading ? (
          <div className="session-list-loading">
            <Spin size="small" />
            <Text type="secondary" style={{ marginLeft: 8 }}>加载中...</Text>
          </div>
        ) : sessions.length === 0 ? (
          <Empty 
            image={Empty.PRESENTED_IMAGE_SIMPLE}
            description="暂无会话"
            style={{ padding: '20px 0', background: 'rgba(255, 255, 255, 0.45)'}}
          >
          </Empty>
        ) : (
          <List
            dataSource={sessions}
            renderItem={(session) => (
              <List.Item
                className={`session-item ${currentSessionId === session.id ? 'active' : ''}`}
                onClick={() => handleSessionSelect(session)}
              >
                <div className="session-item-content">
                  <div className="session-item-header">
                    {editingSessionId === session.id ? (
                      <div className="session-edit-input">
                        <Input
                          value={editingTitle}
                          onChange={(e) => setEditingTitle(e.target.value)}
                          onPressEnter={saveEditing}
                          size="small"
                          autoFocus
                        />
                        <div className="session-edit-actions">
                          <Button 
                            type="text" 
                            icon={<CheckOutlined />} 
                            size="small"
                            onClick={saveEditing}
                          />
                          <Button 
                            type="text" 
                            icon={<CloseOutlined />} 
                            size="small"
                            onClick={cancelEditing}
                          />
                        </div>
                      </div>
                    ) : (
                      <>
                        <Text 
                          className="session-title" 
                          ellipsis={{ tooltip: session.session_title }}
                        >
                          {session.session_title}
                        </Text>
                        <div className="session-actions">
                          <Tooltip title="重命名">
                            <Button 
                              type="text" 
                              icon={<EditOutlined />} 
                              size="small"
                              onClick={(e) => {
                                e.stopPropagation();
                                startEditing(session);
                              }}
                            />
                          </Tooltip>
                          <Popconfirm
                            title="确定要删除这个会话吗？"
                            description="删除后将无法恢复会话中的所有消息"
                            onConfirm={(e) => {
                              e.stopPropagation();
                              handleDeleteSession(session.id);
                            }}
                            okText="删除"
                            cancelText="取消"
                            okType="danger"
                          >
                            <Button 
                              type="text" 
                              icon={<DeleteOutlined />} 
                              size="small"
                              danger
                              onClick={(e) => e.stopPropagation()}
                            />
                          </Popconfirm>
                        </div>
                      </>
                    )}
                  </div>
                </div>
              </List.Item>
            )}
          />
        )}
      </div>

      {/* 创建会话模态框 */}
      <Modal
        title="创建新会话"
        open={createModalVisible}
        onOk={handleCreateSession}
        onCancel={() => {
          setCreateModalVisible(false);
          setNewSessionTitle('');
        }}
        okText="创建"
        cancelText="取消"
      >
        <Input
          placeholder="请输入会话标题"
          value={newSessionTitle}
          onChange={(e) => setNewSessionTitle(e.target.value)}
          onPressEnter={handleCreateSession}
          maxLength={50}
        />
      </Modal>
    </div>
  );
};

export default SessionList;